<template>
    <div class="agent-detail">
        <Header />
        <PageBanner
            title="经纪人详情"
            :breadcrumbs="[
                { title: '经纪人详情' }
            ]"
        />
        
        <div class="container">
            <div class="content-wrapper">
                <!-- 经纪人基本信息 -->
                <div class="agent-info-card">
                    <div class="agent-basic">
                        <div class="avatar">
                            <img :src="getFullImageUrl(agent.avatar) || defaultAvatar" :alt="agent.name">
                        </div>
                        <div class="info">
                            <div class="name-title">
                                <h2>{{ agent.name }}</h2>
                                <span class="title">{{ agent.title }}</span>
                            </div>
                            <div class="stats">
                                <div class="stat-item">
                                    <span class="label">成交</span>
                                    <span class="value">{{ agent.deals }}套</span>
                                </div>
                                <div class="stat-item">
                                    <span class="label">好评率</span>
                                    <span class="value">{{ agent.rating }}%</span>
                                </div>
                                <div class="stat-item">
                                    <span class="label">从业经验</span>
                                    <span class="value">{{ agent.experience }}年</span>
                                </div>
                            </div>
                            <div class="tags">
                                <span v-for="tag in agent.tags" 
                                      :key="tag" 
                                      class="tag">{{ tag }}</span>
                            </div>
                        </div>
                        <div class="contact">
                            <AgentContact 
                                v-if="agent.id"
                                :agent-id="agent.id"
                                :agent-name="agent.name" 
                                :agent-phone="agent.phone" 
                                :agent-wechat="agent.wechat"
                                :mode="'card'"
                                @start-chat="startChat" 
                            />
                            <div v-else class="loading-contact">
                                <el-skeleton animated :rows="3" />
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 经纪人介绍 -->
                <div class="agent-intro card">
                    <h3>个人介绍</h3>
                    <p>{{ agent.introduction }}</p>
                </div>

                <!-- 在售房源 -->
                <div class="agent-houses card" v-if="agent.houses && agent.houses.length > 0">
                    <h3>在售房源</h3>
                    <div class="house-grid">
                        <div v-for="house in agent.houses" 
                             :key="house.id" 
                             class="house-card"
                             @click="router.push(`/house/${house.id}`)">
                            <img :src="getFullImageUrl(house.image)" :alt="house.title">
                            <div class="house-info">
                                <h4>{{ house.title }}</h4>
                                <p class="price">¥{{ house.price }}万</p>
                                <div class="attrs">
                                    <span>{{ house.area }}㎡</span>
                                    <span>{{ house.layout }}</span>
                                    <span>{{ house.direction }}</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 客户评价 -->
                <div class="agent-reviews card" v-if="agent.reviews && agent.reviews.length > 0">
                    <h3>客户评价</h3>
                    <div class="review-list">
                        <div v-for="review in agent.reviews" 
                             :key="review.id" 
                             class="review-item">
                            <div class="review-header">
                                <img :src="getFullImageUrl(review.avatar) || defaultAvatar" :alt="review.name" class="reviewer-avatar">
                                <div class="reviewer-info">
                                    <span class="name">{{ review.name }}</span>
                                    <el-rate v-model="review.rating" disabled />
                                </div>
                                <span class="time">{{ review.time }}</span>
                            </div>
                            <p class="review-content">{{ review.content }}</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <Footer />
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import Header from '@/views/common/Header.vue'
import Footer from '@/views/common/Footer.vue'
import PageBanner from '@/views/common/PageBanner.vue'
import { useUserStore } from '@/stores/user'
import { useLoginStore } from '@/stores/login'
import AgentContact from './AgentContact.vue'
import { getAgentInfo } from '@/api/agent'
import { ElMessage, ElLoading } from 'element-plus'
import { getFullImageUrl, getAvatarUrl } from '@/utils/imageUrl'

// 默认头像
const defaultAvatar = 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()
const loginStore = useLoginStore()

// 经纪人详情数据
const agent = ref({
    id: '',
    name: '',
    title: '',
    avatar: '',
    deals: 0,
    rating: 0,
    experience: 0,
    phone: '',
    wechat: '',
    tags: [],
    introduction: '',
    houses: [],
    reviews: []
})

const loading = ref(false)

// 获取经纪人详情
const fetchAgentDetail = async (agentId) => {
    if (!agentId) {
        ElMessage.error('经纪人ID无效')
        return
    }
    
    loading.value = true
    const loadingInstance = ElLoading.service({
        lock: true,
        text: '加载中...',
        background: 'rgba(255, 255, 255, 0.7)'
    })
    
    try {
        console.log('获取经纪人详情: agentId=', agentId)
        const res = await getAgentInfo(agentId)
        console.log('获取经纪人详情响应:', res)
        
        if (res.code === 200 && res.data) {
            const agentData = res.data
            agent.value = {
                id: agentData.agentId,
                name: agentData.realName || '未知经纪人',
                title: agentData.position || agentData.title || '房产顾问',
                avatar: agentData.avatar || '',
                deals: agentData.deals || 0,
                // 如果有ratingPercent字段就用它，否则将rating(0-5)转换为百分比(0-100)
                rating: agentData.ratingPercent || (agentData.rating ? agentData.rating * 20 : 0),
                experience: agentData.workYears || 0,
                phone: agentData.phone || '',
                wechat: agentData.wechat || '',
                // 如果tags是字符串，尝试按逗号分割；如果是null/undefined，使用空数组
                tags: agentData.expertise ? 
                      agentData.expertise.split(',').map(tag => tag.trim()).filter(tag => tag) : 
                      [],
                introduction: agentData.introduction || agentData.remark || '暂无介绍',
                // 暂时设为空数组，后续可能需要单独的API获取经纪人的房源列表
                houses: agentData.houses || [],
                reviews: agentData.reviews || []
            }
            console.log('处理后的经纪人数据:', agent.value)
        } else {
            ElMessage.error(res.msg || '获取经纪人详情失败')
        }
    } catch (error) {
        console.error('获取经纪人详情失败:', error)
        ElMessage.error('获取经纪人详情失败，请稍后重试')
    } finally {
        loading.value = false
        loadingInstance.close()
    }
}

onMounted(() => {
    // 根据路由参数获取经纪人详情
    const agentId = route.params.id
    if (agentId) {
        fetchAgentDetail(agentId)
    } else {
        ElMessage.warning('未找到经纪人信息')
        router.push('/agent')
    }
})

// 继续聊天功能
const startChat = () => {
    if (!userStore.isLoggedIn) {
        loginStore.showLogin()
        return
    }
    
    // 将经纪人信息传递到聊天页面
    router.push({
        path: '/chat',
        query: {
            agentId: agent.value.id,
            agentName: agent.value.name,
            agentAvatar: getFullImageUrl(agent.value.avatar) || defaultAvatar
        }
    })
}
</script>

<style lang="scss" scoped>
.agent-detail {
    width: 1920px;
    margin: 0 auto;

    .container {
        padding: 40px 60px;
        
        .content-wrapper {
            max-width: 1320px;
            margin: 0 auto;
        }
    }

    .card {
        background: #fff;
        border-radius: 8px;
        padding: 24px;
        margin-bottom: 24px;
        box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);

        h3 {
            font-size: 20px;
            color: #2F3B59;
            margin-bottom: 20px;
            padding-bottom: 16px;
            border-bottom: 1px solid #eee;
        }
    }

    .agent-info-card {
        @extend .card;

        .agent-basic {
            display: flex;
            gap: 24px;

            .avatar {
                width: 160px;
                height: 160px;
                border-radius: 50%;
                overflow: hidden;

                img {
                    width: 100%;
                    height: 100%;
                    object-fit: cover;
                }
            }

            .info {
                flex: 1;

                .name-title {
                    margin-bottom: 16px;

                    h2 {
                        font-size: 24px;
                        color: #2F3B59;
                        margin-bottom: 8px;
                    }

                    .title {
                        color: #666;
                    }
                }

                .stats {
                    display: flex;
                    gap: 32px;
                    margin-bottom: 16px;

                    .stat-item {
                        .label {
                            color: #666;
                            margin-right: 8px;
                        }

                        .value {
                            color: #4A60A1;
                            font-weight: 500;
                        }
                    }
                }

                .tags {
                    display: flex;
                    flex-wrap: wrap;
                    gap: 8px;

                    .tag {
                        padding: 4px 12px;
                        background: #f5f5f5;
                        border-radius: 4px;
                        font-size: 12px;
                        color: #666;
                    }
                }
            }

            .contact {
                text-align: center;
            }
        }
    }

    .house-grid {
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        gap: 24px;

        .house-card {
            cursor: pointer;
            transition: transform 0.3s;

            &:hover {
                transform: translateY(-5px);
            }

            img {
                width: 100%;
                height: 200px;
                object-fit: cover;
                border-radius: 8px;
                margin-bottom: 12px;
            }

            .house-info {
                h4 {
                    font-size: 16px;
                    color: #2F3B59;
                    margin-bottom: 8px;
                }

                .price {
                    color: #f56c6c;
                    font-size: 18px;
                    margin-bottom: 8px;
                }

                .attrs {
                    display: flex;
                    gap: 12px;
                    color: #666;
                    font-size: 14px;
                }
            }
        }
    }

    .review-list {
        .review-item {
            padding: 20px 0;
            border-bottom: 1px solid #eee;

            &:last-child {
                border-bottom: none;
            }

            .review-header {
                display: flex;
                align-items: center;
                margin-bottom: 12px;

                .reviewer-avatar {
                    width: 40px;
                    height: 40px;
                    border-radius: 50%;
                    margin-right: 12px;
                }

                .reviewer-info {
                    flex: 1;

                    .name {
                        display: block;
                        color: #2F3B59;
                        margin-bottom: 4px;
                    }
                }

                .time {
                    color: #999;
                }
            }

            .review-content {
                color: #666;
                line-height: 1.6;
            }
        }
    }

    .loading-contact {
        width: 100%;
        min-height: 120px;
        padding: 20px;
        border-radius: 8px;
        background: rgba(240, 240, 240, 0.5);
    }
}
</style> 